package com.gupao.delegate.springmvc;


import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

public class DispatcherServlet extends HttpServlet {

    private List<Handler> handlerList = new ArrayList<Handler>();
    @Override
    public void init() throws ServletException {
        try {
            Class<?> systemControllerClazz = SystemController.class;
            Handler systemHandler = new Handler();
            systemHandler.setController(systemControllerClazz.newInstance());
            systemHandler.setMethod(systemControllerClazz.getMethod("Login", new Class[]{String.class, String.class}));
            systemHandler.setUrl("/web/login");
            handlerList.add(systemHandler);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        doDispatch(req, res);
    }

    private void doDispatch(HttpServletRequest req, HttpServletResponse res) {
        String url = req.getRequestURI();
        Handler handler = null;
        try {
            for(Handler h : handlerList){
                if(url.equals(h.getUrl())){
                    handler = h;
                    break;
                }
            }
            Object obj = null;
            obj = handler.getMethod().invoke(handler.getController(), req.getParameter("username"), req.getParameter("password"));
            System.out.println(obj);
            ServletOutputStream sos = res.getOutputStream();
            byte[] dataBytes = obj.toString().getBytes();
            sos.write(dataBytes);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    class Handler{
        private String url;
        private Method method;
        private Object Controller;

        public String getUrl() {
            return url;
        }

        public void setUrl(String url) {
            this.url = url;
        }

        public Method getMethod() {
            return method;
        }

        public void setMethod(Method method) {
            this.method = method;
        }

        public Object getController() {
            return Controller;
        }

        public void setController(Object controller) {
            Controller = controller;
        }
    }
}
